# -*- coding: UTF-8 -*-
# *******************************************************************
# File Name: general_utils
# > Author: 04000387
# > Created Time: 2024/12/23 17:09
# *******************************************************************
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon, Rectangle


def _get_box_min_max(img, boxes, scale=1, offset=5):
    x_min = 0
    x_max = 0
    y_min = 0
    y_max = 0

    for item in boxes:
        for it in item:
            if it[0] < x_min:
                x_min = it[0]
            elif it[0] >= x_max:
                x_max = it[0]

            if it[1] < y_min:
                y_min = it[1]

            elif it[1] >= y_max:
                y_max = it[1]

    offset_scale = scale * offset
    x_min -= offset_scale
    x_max += offset_scale
    y_min -= offset_scale
    y_max += offset_scale

    if img is not None:
        x_min = 0
        y_min = 0
        x_max = img.shape[1]
        y_max = img.shape[0]

    return x_min, x_max, y_min, y_max


def plot_box(img, boxes, edge_color="b"):
    fig, ax = plt.subplots()
    if img is not None:
        ax.imshow(img)

    for item in boxes:
        patch = Rectangle(item[:2], item[2], item[3], linewidth=1, edgecolor=edge_color, facecolor='none')
        ax.add_patch(patch)

    plt.show()


def plot_box_four_point(img, boxes, edge_color="b"):
    """
    根据四个顶点画图
    :param img: 图片,没有图片置为None
    :param boxes: 框,必填
    :param edge_color: 边框颜色
    :return: r
    """
    fig, ax = plt.subplots()
    if img is not None:
        ax.imshow(img)
    for item in boxes:
        patch = Polygon(item, closed=True, edgecolor=edge_color, fill=None)
        ax.add_patch(patch)

    x_min, x_max, y_min, y_max = _get_box_min_max(img, boxes)

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_max, y_min)

    plt.show()
